package util
class Helper {
	static Object withJndiCtx(java.util.Map userProps = [:], Closure closure) {
		def props = new Properties()
		props.setProperty('java.naming.factory.initial', 'org.jnp.interfaces.NamingContextFactory')
		props.setProperty('java.naming.factory.url.pkgs', 'org.jboss.naming:org.jnp.interfaces')
		props.putAll(userProps)
		def ctx = new javax.naming.InitialContext(props)
		try {
			return closure.call(ctx)
		} finally {
			ctx.close()
		}
	}		
	static Object withJmsConn(Closure closure) {
		def cf = withJndiCtx { ctx -> ctx.lookup("ConnectionFactory") }
		def conn = cf.createConnection()
		try {
			return closure.call(conn)
		} finally {
			conn.close()
		}
	}
	
	static String getStackTraceString(Throwable t) {		
		def sb = new StringWriter(256)
		sb.withPrintWriter{ pw -> t.printStackTrace(pw) }
		return sb.toString()
	}
	
	static String inspect(Object obj) {
		if (obj == null){
			return "null"
		}
		def sb = new StringBuilder(256)
		sb.append("[")
		def cls = obj.getClass()
		def beanInfo = java.beans.Introspector.getBeanInfo(cls)
		beanInfo.propertyDescriptors.each { pd ->
			try {
				sb.append("  ${pd.displayName}: ")
				def val = pd.readMethod.invoke(obj)
				if (val != null && (val.getClass().isArray() || val instanceof Enumeration)) {
					val = val.toList()
				}
				sb.append(val.toString()+"\n")
			} catch (Exception e) {
				sb.append("Error: " + getStackTraceString(e))
			}
		}
		sb.append("]\n")
		return sb.toString()
	}
}